const dbApi = require('../models/db')
// const jwt = require('../utils/jwt')
// const { uuid } = require('../config/config.default')
// 查询粉丝列表
exports.getFansList = async (req, res, next) => {
  let { page = 0 } = req.query
  const { username } = req.query
  page = page > 1 ? (page - 1) * 15 : 0
  const sql = `SELECT a.follower,a.be_follower as beFollower,b.avatar,b.gender
  FROM fans a INNER JOIN users b on a.follower =b.username WHERE be_follower = '${username}' ORDER BY a.time DESC LIMIT  ${page},15 `
  const sql1 = `SELECT COUNT(*) as count
  FROM fans WHERE be_follower = '${username}'`
  const sql2 = `SELECT be_follower as beFollower FROM fans WHERE follower = '${username}'`
  try {
    const data = await dbApi.query(sql)
    const data1 = await dbApi.query(sql2)
    data.forEach((item, index) => {
      const other = data1.some((value, index) => {
        return value.beFollower === item.follower
      })
      item.others = other
    })
    const [listcount] = await dbApi.query(sql1)
    res.status(200).json({
      fansList: data,
      count: listcount.count,
      message: 'success'
    })
  } catch (error) {
    next(error)
  }
}

// 关注用户
exports.setAttentionStatus = async (req, res, next) => {
  const { beFollower } = req.body
  const sql = `INSERT INTO fans (follower,be_follower)
    VALUES ('${req.user.username}','${beFollower}') `
  try {
    const { affectedRows: data } = await dbApi.query(sql)
    data
      ? res.status(201).json({
        message: 'succeed'
      })
      : res.status(400).json({
        message: 'Invalid request'
      })
  } catch (error) {
    next(error)
  }
}

// 取消关注用户
exports.delAttention = async (req, res, next) => {
  const { beFollower } = req.body
  const sql = `DELETE FROM fans WHERE follower ='${req.user.username}' AND be_follower ='${beFollower}'`
  try {
    const { affectedRows: data } = await dbApi.query(sql)
    data
      ? res.status(201).json({
        message: 'succeed'
      })
      : res.status(400).json({
        message: 'Invalid request'
      })
  } catch (error) {
    next(error)
  }
}
